//
//  FMDBManager.m
//  BaseProject
//
//  Created by KH_MoSi on 2020/11/6.
//  Copyright © 2020 王盼盼. All rights reserved.
//

#import "FMDBManager.h"
#import "FMDB.h"
@interface FMDBManager ()

@end
static FMDatabase *database;
@implementation FMDBManager
+ (void)initialize
{
    //NSLog(@"initialize");
    //1.获取文件路径
    NSString *documentsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject;
    NSString *statisticDir = [documentsPath stringByAppendingPathComponent:@"Statistic"];
    if (![[NSFileManager defaultManager]fileExistsAtPath:statisticDir]) {
        [[NSFileManager defaultManager]createDirectoryAtPath:statisticDir withIntermediateDirectories:YES attributes:nil error:nil];
    }
    NSString *databasePath = [statisticDir stringByAppendingPathComponent:@"userBehavior.db"];
//    NSLog(@"databasePath:%@",databasePath);
    //2.创建数据
    database = [FMDatabase databaseWithPath:databasePath];
    //3.打开数据库
    if (![database open]) {
        return;
    }
    //4.执行sql
    [database beginTransaction];
    //id name date duration flag isLogin
    [database executeUpdate:@"CREATE TABLE IF NOT EXISTS t_statistic_behavior(id integer NOT NULL PRIMARY KEY AUTOINCREMENT, name text NOT NULL, date text NOT NULL, duration real NOT NULL, flag text NOT NULL, isLogin text NOT NULL);"];
    [database commit];
}
+ (void)addDataWithName:(NSString *)name withDate:(NSString *)date withDuration:(NSTimeInterval)duration withFlag:(NSString *)flag withIsLogin:(NSString *)isLogin
{
    //NSLog(@"addData");
    duration = fabs(duration);
    [database beginTransaction];
    [database executeUpdateWithFormat:@"INSERT INTO t_statistic_behavior(name,date,duration,flag,isLogin) VALUES(%@,%@,%f,%@,%@);",name,date,duration,flag,isLogin];
    [database commit];
    
    if ([database hadError]) {
        NSLog(@"插入数据库失败");
    } else {
        NSLog(@"插入数据库 成功");
    }
}
+ (NSArray *)queryData
{
    NSMutableArray *mutableArray = [NSMutableArray array];
    NSString *sql = [NSString stringWithFormat:@"select * from t_statistic_behavior"];
    FMResultSet *set = [database executeQuery:sql];
    while ([set next]) {
        NSMutableDictionary *dict = [[NSMutableDictionary alloc]initWithDictionary:[set resultDictionary]];
        [mutableArray addObject:dict];
    }
    [set close];
    return mutableArray.copy;
}
+ (void)removeData
{
    [database beginTransaction];
    [database executeUpdate:@"DELETE FROM t_statistic_behavior"];
    [database commit];
}
@end
